package com.tedu.day08springmvc.controller;

import com.tedu.day08springmvc.mapper.UserMapper;
import com.tedu.day08springmvc.pojo.VO.UserVO;
import com.tedu.day08springmvc.pojo.dto.UserDTO;
import com.tedu.day08springmvc.pojo.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//@Controller
@RestController//不用再打@ResponseBody注解了
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping(value = "/users/reg")
    //@ResponseBody
    public String reg(UserDTO userDTO) {
        User user = new User();
        System.out.println(user);
        //Spring核心框架提供了一个工具,可以边界的拷贝对象属性值
        //要保证两个对象的属性的类型和名字一致
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());//设置注册时间
        System.out.println(user);
        userMapper.insertUser(user);
        return "注册成功";
    }
    @DeleteMapping("/users/delete/{id}")
    //@ResponseBody
    public String delete(@PathVariable int id){
        int num = userMapper.deleteUser(id);
        return num>0?"删除成功":"删除失败";
    }
    @RequestMapping("/users/update")
    //@ResponseBody
    public String update(UserDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        int num = userMapper.updateUser(user);
        return num>0?"修改成功":"修改失败";
    }

    //@RequestMapping(value = "/users/find",method = RequestMethod.GET)
    @GetMapping("/users/find/{id}")
    //@ResponseBody
    public List<UserVO> find(){
        //直接将UserMapper查询出来的集合返回即可
        List<UserVO> userList = userMapper.selectUsers();
        return userList;
    }


    //查询用户信息
    @GetMapping("/users/findById/{id}")
    public UserVO findById(@PathVariable int id){
        UserVO userVO = userMapper.findById(id);
        return userVO;
    }
}
